/*******************************************************************************
* Copyright (c) 2010, 2018 西安秦晔信息科技有限公司
* Licensed under the Apache License, Version 2.0 (the "License");
*    you may not use this file except in compliance with the License.
*    You may obtain a copy of the License at
*
*       http://www.apache.org/licenses/LICENSE-2.0
*
*    Unless required by applicable law or agreed to in writing, software
*    distributed under the License is distributed on an "AS IS" BASIS,
*    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*    See the License for the specific language governing permissions and
*    limitations under the License.
*******************************************************************************/
package com.qinyeit.webapp.controller.management.dishes;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.qinyeit.serviceapp.entity.*;
import com.qinyeit.serviceapp.entity.enums.State;
import com.qinyeit.serviceapp.exception.BusinessRunTimeException;
import com.qinyeit.serviceapp.service.dishes.*;
import com.qinyeit.serviceapp.service.organization.BranchService;
import com.qinyeit.serviceapp.service.organization.DistrictService;
import com.qinyeit.webapp.controller.management.BaseManagementController;
import com.qinyeit.webapp.utils.CurrentAccountUtils;
import com.qinyeit.webapp.utils.SearchableUtils;
import com.qinyetech.springstage.core.entity.search.Searchable;
import com.qinyetech.springstage.core.lang.QyMap;
import com.qinyetech.springstage.core.utils.JSONUtils;
import com.qinyetech.springstage.core.web.annotation.PageableDefaults;
import com.qinyetech.springstage.core.web.annotation.PermissionInfo;
import com.qinyetech.springstage.core.web.dto.ResponseResult;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * ClassName: ChangePricesController <br/>
 * Function: changePrice [菜品变价单] <br/>
 * date: 2018-11-27 15:11:36 <br/>
 *
 * @author liuwenjin
 * @version  1.0
 * @since JDK 1.8
 */
@RestController
@RequestMapping("/management/dishes/changePrices")
@PermissionInfo(parentName ="基础信息管理" ,parentOrder = 10,order = 10,code = "management_changePrice:read",name ="菜品变价单",deleteAble = false)
public class ChangePricesController extends BaseManagementController{

	@Autowired
	private ChangePriceService changePriceService;
	@Autowired
    private DishesMenuService dishesMenuService;
	@Autowired
    private DishesService dishesService;
	@Autowired
    private ChangePriceBranchService changePriceBranchService;
	@Autowired
    private ChangePriceLogService changePriceLogService;
	@Autowired
    private DistrictService districtService;
	@Autowired
    private DishesSpecificationService dishesSpecificationService;
	@Autowired
    private BranchService branchService;

	@Autowired
    private DishesMenuBranchService dishesMenuBranchService;


	private final String [] keys = {"id","menuId","dishesId","specId","oldPrice","price","oldVipPrice","vipPrice","reason",
            "effectiveTime","state","operatorName","operateTime","dishesName"};

    @RequiresPermissions("management_changePrice:show")
    @PermissionInfo(code = "management_changePrice:show",name ="查看",deleteAble = false)
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST})
    @PageableDefaults(sort = "id=desc")//默认按照id降序
    public ResponseResult<JSONObject> index(String name,String state,Long districtId,Searchable searchable){
        Page<Map<String,Object>> changePricePage = changePriceService.findDataByPage(searchable,name,state,districtId,CurrentAccountUtils.getAuthenticatedMerchantGroupID());
        //区域
        searchable = SearchableUtils.newSearchableWithMerchantFilter();
        searchable.addSearchParam("parentId_ne",0);
        List<District> list=districtService.findWithSort(searchable);
        QyMap map = QyMap.map("states",State.values());
        map.setv("districts",list);
        map.setv("changePricePage",changePricePage);
        return ok("查询成功", map);
    }

    @GetMapping("/create")
    public ResponseResult<QyMap> _new(){
        QyMap map=QyMap.NEW();
        map.setv("changePrice",JSONUtils.include(new ChangePrice(), keys));
        initFormDate(map);
        return ok("初始化成功", map);
    }

    @RequiresPermissions("management_changePrice:create")
    @PermissionInfo(code = "management_changePrice:create",name ="新增",deleteAble = false)
    @PostMapping("/create")
    public ResponseResult<String> create(@RequestBody JSONObject changePrice, BindingResult bindingResult){
//        if(changePriceService.exists(buildExists(null, "no", changePrice.getNo()))){
//             bindingResult.rejectValue("no","no.error","编号已经存在");
//        }
        if (bindingResult.hasErrors()) {
            return super.validateFail(bindingResult);
        }
        changePriceService.saveData(changePrice, CurrentAccountUtils.getAuthenticatedMerchantGroupID(),CurrentAccountUtils.getAuthenticatedEmployeeName());
        return ok("保存成功");
    }

    @GetMapping("/{id}")
    public ResponseResult<JSONObject> show(@ModelAttribute ChangePrice changePrice){
        return ok("查询成功", JSONUtils.include(changePrice, keys));
    }

    @GetMapping("/{id}/update")
    public ResponseResult<QyMap> edit(@ModelAttribute ChangePrice changePrice){
        QyMap map=QyMap.NEW();

        Dishes dishes = dishesService.findById(changePrice.getDishesId());
        changePrice.setDishesName(dishes.getName());
        map.setv("changePrice",JSONUtils.include(changePrice, keys));
        initFormDate(map);

        //生效机构
        Searchable searchable = SearchableUtils.newSearchableWithMerchantFilter();
        searchable.addSearchParam("changePriceId_eq",changePrice.getId());
        List<ChangePriceBranch> branchList = changePriceBranchService.findWithSort(searchable);
        Branch branchEn = null;
        if(CollectionUtils.isNotEmpty(branchList)){
            for (ChangePriceBranch priceBranch : branchList) {
                branchEn = branchService.findById(priceBranch.getBranchId());
                priceBranch.setLabel(branchEn.getName());
            }
        }
        map.setv("branchList",JSONUtils.include(branchList,"branchId","districtId","label"));

        List<Long> branchIds = Lists.newArrayList();
        //获取菜谱下的适用门店
        searchable = SearchableUtils.newSearchableWithMerchantFilter();
        searchable.addSearchParam("menuId_eq",changePrice.getMenuId());
        List<DishesMenuBranch> branchs = dishesMenuBranchService.findWithSort(searchable);
        if(CollectionUtils.isNotEmpty(branchs)){
            for (DishesMenuBranch branch : branchs) {
                branchIds.add(branch.getBranchId());
            }
        }
        //区域
        List<District> list=districtService.getBuildTree(CurrentAccountUtils.getAuthenticatedMerchantGroupID(),true,branchIds,true);
        map.setv("districts",list);
        return ok("查询成功",map);
    }

    @RequiresPermissions("management_changePrice:update")
    @PermissionInfo(code = "management_changePrice:update",name ="修改",deleteAble = false)
    @PutMapping("/{id}/update")
    public ResponseResult<String> update(@RequestBody JSONObject changePrice,  BindingResult bindingResult){
//        if(changePriceService.exists(buildExists(null, "no", changePrice.getNo()))){
//             bindingResult.rejectValue("no","no.error","编号已经存在");
//        }

        if (bindingResult.hasErrors()) {
            return super.validateFail(bindingResult);
        }
        changePriceService.updateData(changePrice,CurrentAccountUtils.getAuthenticatedEmployeeName());
        return ok("更新成功", null);
    }

    @RequiresPermissions("management_changePrice:destory")
    @PermissionInfo(code = "management_changePrice:destory",name ="删除",deleteAble = false)
    @DeleteMapping("/{id}")
    public ResponseResult<String> destory(@PathVariable Long id){
        changePriceService.logicDelete(id);
        return ok("删除成功", null);
    }

    /**
     * 修改状态
     *
     * @param id
     * @return
     */
    @RequiresPermissions("management_changePrice:updateState")
    @PermissionInfo(code = "management_changePrice:updateState",name ="修改状态",deleteAble = false)
    @GetMapping("/updateState")
    public ResponseResult<String> updateState(Long id){
        ChangePrice changePrice = changePriceService.findById(id);
        if(changePrice.getState()== State.NORMAL){
            changePrice.setState(State.DISABLED);
        }else {
            changePrice.setState(State.NORMAL);
        }
        changePriceService.update(changePrice);
        return ok("操作成功", null);
    }


    /**
     * 查看历史
     *
     * @param id
     * @return
     */
    @RequiresPermissions("management_dishesMenu:showHistory")
    @PermissionInfo(code = "management_dishesMenu:showHistory",name ="查看历史",deleteAble = false)
    @GetMapping("/showHistory")
    public ResponseResult<String> showHistory(Long id){
        ChangePrice changePrice = changePriceService.findById(id);
        if(changePrice==null){
            throw new BusinessRunTimeException("变价不存在",10001);
        }
        Dishes dishes = dishesService.findById(changePrice.getDishesId());
        changePrice.setDishesName(dishes.getName());
        QyMap map = QyMap.map("changePrice",JSONUtils.include(changePrice,"id","dishesName"));

        Searchable searchable = SearchableUtils.newSearchableWithMerchantFilter();
        searchable.addSearchParam("changePriceId_eq",id);
        searchable.addSort(Sort.Direction.ASC,"operateTime");
        List<ChangePriceLog> logList = changePriceLogService.findWithSort(searchable);
        map.setv("logList",JSONUtils.include(logList,"dishesName","specName",
                "oldPrice","price","oldVipPrice","vipPrice","reason","effectiveTime","operatorName","operateTime"));
        return ok("操作成功", map);
    }




    @ModelAttribute
    public void preparedData(@PathVariable(value="id",required = false) String id,Model model){
        if(StringUtils.isNotBlank(id)){ //如果路径中有id参数则查询实体对象
            ChangePrice changePrice = changePriceService.findById(Long.valueOf(id));
            model.addAttribute(changePrice);
        }
    }

    /**
     * 初始化表单数据
     * @param qyMap
     */
    private void initFormDate(QyMap qyMap){
        //菜谱
        Searchable searchable = SearchableUtils.newSearchableWithMerchantFilter();
        searchable.addSearchParam("state_eq", State.NORMAL);
        List<DishesMenu> menuList = dishesMenuService.findWithSort(searchable);
        qyMap.setv("menuList",JSONUtils.include(menuList,"id","name"));



    }

}